import LayerStatic from "../common/LayerStatic";
import Utils from "../core/Utils";

const { ccclass, property } = cc._decorator;

@ccclass
export default class Block extends cc.Component {

    @property(cc.Sprite)
    skin: cc.Sprite = null;
    @property(cc.Node)
    coverNode: cc.Node = null;


    //是否在缓冲区
    public isInBuffer: boolean = false;
    //处在缓存区的第几堆，在被tackout时才会被赋值
    public indexOfBuffer: Array<number> = null;
    //默认状态封闭，用于控制遮罩层是否显示
    public isClosed: boolean = false;
    //是否已经被点击，确保回收区的方框不能被点击
    public isClicked: boolean = false;
    //保存原始坐标
    public originalPos: cc.Vec2;
    //保存在方块列表中的下标
    public indexInList: number[];
    //方块的类型
    public type: number;
    public row: number;
    public line: number;
    //初始的显示状态
    public moldType: number;
    public baseGridList: number[][];
    public layerOnGrid: number[];


    public isDestroy: boolean = false;
    public isMoveTarget: boolean = false;
    private isDestroying: boolean = false;

    onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchCancel, this);
    }

    init(data: { type: number, rowNum: number, line: number, moldType: number }, index: number[], pos: cc.Vec2, coverMap: number[][]) {
        //保存原始坐标
        this.originalPos = pos;
        //保存在方块列表中的下标
        this.indexInList = index;
        //保存配置信息： 行，列数, 摆放类型
        this.type = data["type"];
        this.row = data["rowNum"];
        this.line = data["rolNum"];
        this.moldType = data["moldType"];
        //计算对应遮挡层的四个网格下标
        this.skin.node.active = this.moldType === 1;
        let x = Math.floor(this.row / 4);
        let y = Math.floor(this.line / 4);
        this.baseGridList = [[x, y], [x, y + 1], [x + 1, y], [x + 1, y + 1]];
        //保存当前方块在对应四个网格上的已经覆盖的层数（相当于记录自己所在的层数，从1开始）
        this.layerOnGrid = [
            coverMap[x][y] + 1,
            coverMap[x][y + 1] + 1,
            coverMap[x + 1][y] + 1,
            coverMap[x + 1][y + 1] + 1,
        ];
        //刷新遮挡层数据（相当于把自己再加上去，好方便楼上的邻居统计）
        LayerStatic.GameStatic.flushCoverMap(this.baseGridList, 1);
    }

    protected onEnable(): void {
        this.node.scale = 0;
        cc.tween(this.node).to(0.3, { scale: 1 }).start();
    }

    start() {

    }

    onTouchStart() {
        if (LayerStatic.GameStatic.isGameOver) return;
        if (this.isClosed || this.isClicked) return;
        this.node.zIndex += 100;
        cc.tween(this.node).to(0.1, { scale: 1.4 }).start();
    }

    onTouchEnd() {
        if (LayerStatic.GameStatic.isGameOver) return;
        //被压着的或者已经在回收区的不可以被点击
        if (this.isClosed || this.isClicked) return;
        this.isClicked = true;
        this.node.zIndex -= 100;
        cc.tween(this.node).to(0.1, { scale: 1.2 }).start();
        //LayerStatic.GameStatic.blockNodeList[this.indexInList[0]].splice(this.indexInList[1],1);  //--会导致其它方块的下标漂移
        if (this.isInBuffer) {
            this.isClicked = LayerStatic.GameStatic.onBlockInBufferClicked(this);
        } else {
            this.isClicked = LayerStatic.GameStatic.onBlockInMapClicked(this);
        }
        if (!this.isClicked) {
            cc.tween(this.node).to(0.1, { scale: 1 }).start();
        }
    }

    onTouchCancel() {
        if (LayerStatic.GameStatic.isGameOver) return;
        if (this.isClosed || this.isClicked) return;
        this.node.zIndex -= 100;
        cc.tween(this.node).to(0.1, { scale: 1 }).start();
    }

    //返回道具
    goBack(parNode: cc.Node) {
        Utils.Instance.changeParentNode(this.node, parNode);
        if (parNode === LayerStatic.GameStatic.mapArea) {
            cc.tween(this.node)
                .to(0.05, { position: cc.v3(this.originalPos), scale: 1 })
                .call(() => {
                    this.isClicked = false;
                    LayerStatic.GameStatic.flushCoverMap(this.baseGridList, 1);
                    LayerStatic.GameStatic.setBlockState();
                })
                .start();
        } else {
            cc.tween(this.node)
                .to(0.05, { position: cc.v3(this.originalPos) })
                .call(() => {
                    this.isClicked = false;
                    LayerStatic.GameStatic.flushBufferArea();
                })
                .start();
        }
    }

    protected onDestroy(): void {
        if (LayerStatic.GameStatic.isGameOver) return;
        let pos = this.node.getPosition();
        let par = this.node.parent;
        Utils.Instance.loadSingleRes("prefabs/removeParticle", cc.Prefab, (res) => {
            if (!res) return;
            let particle = cc.instantiate(res);
            particle.setPosition(pos);
            par.addChild(particle, 10);
        })
    }

    update(dt) {
        if (this.isDestroying) return;
        if (this.node && !this.isClosed) {
            this.coverNode.active = false;
            if (this.moldType === 2) {
                this.skin.node.active = true;
            }
        } else {
            this.coverNode.active = true;
        }
        if (this.isDestroy && this.isMoveTarget) {
            this.isDestroying = true;
            this.node.destroy();
        }
    }
}
